<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>农业数据可视化平台 - 手动刷新版</title>
    <link href="https://cdn.bootcdn.net/ajax/libs/bootstrap/5.1.3/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.bootcdn.net/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <script src="https://cdn.bootcdn.net/ajax/libs/echarts/5.4.0/echarts.min.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/bootstrap/5.1.3/js/bootstrap.bundle.min.js"></script>
    <style>
        .sidebar {
            min-height: 100vh;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
        }
        .main-content {
            background-color: #f8f9fa;
            min-height: 100vh;
        }
        .card {
            border: none;
            border-radius: 15px;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
            transition: transform 0.3s ease;
        }
        .card:hover {
            transform: translateY(-5px);
        }
        .chart-container {
            height: 400px;
            margin: 20px 0;
        }
        .metric-card {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 15px;
        }
        .navbar-brand {
            font-weight: bold;
            color: #667eea !important;
        }
        .search-box {
            background: rgba(255,255,255,0.1);
            border: 1px solid rgba(255,255,255,0.3);
            border-radius: 25px;
            color: white;
        }
        .search-box::placeholder {
            color: rgba(255,255,255,0.7);
        }
        .data-count-info {
            background: linear-gradient(45deg, #28a745, #20c997);
            color: white;
            padding: 10px;
            border-radius: 10px;
            margin-bottom: 15px;
        }
        .filter-applied {
            background: linear-gradient(135deg, #28a745 0%, #20c997 100%) !important;
            box-shadow: 0 0 20px rgba(40, 167, 69, 0.3);
        }
        .filter-applied .search-box {
            background: rgba(255,255,255,0.2);
            border: 2px solid rgba(255,255,255,0.5);
        }
        #filterIndicator {
            animation: pulse 2s infinite;
        }
        @keyframes pulse {
            0% { opacity: 1; }
            50% { opacity: 0.5; }
            100% { opacity: 1; }
        }
        .toast {
            min-width: 300px;
            z-index: 9999;
        }
        .loading-overlay {
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(255, 255, 255, 0.8);
            display: flex;
            align-items: center;
            justify-content: center;
            z-index: 1000;
        }
        /* 刷新按钮样式 */
        .refresh-btn {
            position: relative;
            overflow: hidden;
        }
        .refresh-btn.refreshing {
            pointer-events: none;
        }
        .refresh-btn.refreshing .fa-sync-alt {
            animation: spin 1s linear infinite;
        }
        @keyframes spin {
            from { transform: rotate(0deg); }
            to { transform: rotate(360deg); }
        }
        /* 数据源状态指示器 */
        .data-source-indicator {
            padding: 5px 10px;
            border-radius: 15px;
            font-size: 0.8em;
            margin-left: 10px;
        }
        .data-source-hive {
            background: linear-gradient(45deg, #28a745, #20c997);
            color: white;
        }
        .data-source-mock {
            background: linear-gradient(45deg, #ffc107, #fd7e14);
            color: white;
        }
        /* 刷新状态面板 */
        .refresh-status-panel {
            background: rgba(255,255,255,0.1);
            border: 1px solid rgba(255,255,255,0.2);
            border-radius: 10px;
            padding: 10px;
            margin-top: 15px;
        }
    </style>
</head>
<body>
    <!-- 顶部导航栏 -->
    <nav class="navbar navbar-expand-lg navbar-light bg-white shadow-sm">
        <div class="container-fluid">
            <a class="navbar-brand" href="#">
                <i class="fas fa-seedling me-2"></i>农业数据可视化平台
            </a>
            <div class="navbar-nav ms-auto">
                <div class="nav-item">
                    <span class="badge bg-success me-3" id="dataCountBadge">数据加载中...</span>
                    <span class="data-source-indicator" id="dataSourceIndicator">
                        <i class="fas fa-database"></i> 检测中...
                    </span>
                </div>
                <div class="nav-item me-3">
                    <button class="btn btn-outline-primary btn-sm refresh-btn" onclick="manualRefreshData()" title="手动刷新数据" id="refreshBtn">
                        <i class="fas fa-sync-alt"></i> 刷新
                    </button>
                    <button class="btn btn-outline-success btn-sm ms-1" onclick="exportData()" title="导出数据">
                        <i class="fas fa-download"></i>
                    </button>
                </div>
            </div>
        </div>
    </nav>

    <div class="container-fluid">
        <div class="row">
            <!-- 侧边栏 -->
            <div class="col-md-2 sidebar p-3">
                <h5 class="mb-4"><i class="fas fa-tachometer-alt"></i> 导航菜单</h5>
                
                <!-- 智能搜索框 -->
                <div class="mb-4">
                    <h6><i class="fas fa-search"></i> 智能搜索</h6>
                    <div class="input-group mb-2">
                        <input type="text" class="form-control search-box" id="smartSearch" 
                               placeholder="输入产品名称搜索..." autocomplete="off">
                        <button class="btn btn-outline-light" type="button" onclick="performSearch()">
                            <i class="fas fa-search"></i>
                        </button>
                    </div>
                    <small class="text-light">支持模糊搜索：萝卜、辣椒等</small>
                </div>

                <!-- 全局筛选器 -->
                <div class="mt-4">
                    <h6><i class="fas fa-filter"></i> 数据筛选</h6>
                    <div class="mb-3">
                        <label class="form-label">显示数量</label>
                        <select class="form-select form-select-sm" id="dataLimit">
                            <option value="1000">1,000条</option>
                            <option value="5000" selected>5,000条</option>
                            <option value="10000">10,000条</option>
                            <option value="50000">50,000条</option>
                            <option value="100000">所有数据</option>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">日期范围</label>
                        <select class="form-select form-select-sm" id="dateRange">
                            <option value="7">最近7天</option>
                            <option value="30" selected>最近30天</option>
                            <option value="60">最近60天</option>
                            <option value="180">最近180天</option>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">产品选择</label>
                        <select class="form-select form-select-sm" id="productFilter" multiple size="4">
                            <option value="">加载中...</option>
                        </select>
                        <small class="text-light">按住Ctrl可多选</small>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">产地选择</label>
                        <select class="form-select form-select-sm" id="placeFilter" multiple size="3">
                            <option value="">加载中...</option>
                        </select>
                        <small class="text-light">按住Ctrl可多选</small>
                    </div>
                    <button class="btn btn-light btn-sm w-100" onclick="applyFilters()">
                        <i class="fas fa-search"></i> 应用筛选
                    </button>
                    <button class="btn btn-outline-light btn-sm w-100 mt-2" onclick="resetFilters()">
                        <i class="fas fa-undo"></i> 重置
                    </button>
                    <div class="mt-2">
                        <small class="text-light" id="filterStatus">未应用筛选</small>
                    </div>
                </div>

                <!-- 刷新状态面板 -->
                <div class="refresh-status-panel">
                    <h6><i class="fas fa-sync-alt"></i> 刷新状态</h6>
                    <div class="mb-2">
                        <small class="text-light">上次刷新：</small><br>
                        <small id="lastRefreshTime" class="text-warning">未知</small>
                    </div>
                    <div class="mb-2">
                        <small class="text-light">数据源：</small><br>
                        <small id="dataSourceStatus" class="text-info">检测中...</small>
                    </div>
                    <div class="mb-2">
                        <small class="text-light">记录总数：</small><br>
                        <small id="totalRecordsStatus" class="text-success">-</small>
                    </div>
                    <button class="btn btn-outline-light btn-sm w-100" onclick="manualRefreshData()">
                        <i class="fas fa-sync-alt"></i> 手动刷新
                    </button>
                </div>
            </div>

            <!-- 主内容区 -->
            <div class="col-md-10 main-content p-4">
                <!-- 数据统计信息 -->
                <div class="data-count-info">
                    <div class="row text-center">
                        <div class="col-md-3">
                            <h5 id="totalRecordsDisplay">-</h5>
                            <small>总记录数</small>
                        </div>
                        <div class="col-md-3">
                            <h5 id="uniqueProductsDisplay">-</h5>
                            <small>产品种类</small>
                        </div>
                        <div class="col-md-3">
                            <h5 id="uniquePlacesDisplay">-</h5>
                            <small>产地数量</small>
                        </div>
                        <div class="col-md-3">
                            <h5 id="currentShowingDisplay">-</h5>
                            <small>当前显示</small>
                        </div>
                    </div>
                </div>

                <!-- 概览指标卡片 -->
                <div class="row mb-4">
                    <div class="col-md-3">
                        <div class="card metric-card">
                            <div class="card-body text-center">
                                <i class="fas fa-chart-line fa-2x mb-2"></i>
                                <h4 id="avgPriceToday">-</h4>
                                <p class="mb-0">平均价格(元/斤)</p>
                                <small id="priceChange" class="text-light">-</small>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="card metric-card">
                            <div class="card-body text-center">
                                <i class="fas fa-fire fa-2x mb-2"></i>
                                <h6 id="hotProducts">-</h6>
                                <p class="mb-0">热门产品</p>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="card metric-card">
                            <div class="card-body text-center">
                                <i class="fas fa-weight fa-2x mb-2"></i>
                                <h4 id="totalVolume">-</h4>
                                <p class="mb-0">总交易量</p>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="card metric-card">
                            <div class="card-body text-center">
                                <i class="fas fa-clock fa-2x mb-2"></i>
                                <h6 id="lastUpdate" class="text-light">-</h6>
                                <p class="mb-0">最后更新时间</p>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 价格对比图表 -->
                <div class="row mb-4">
                    <div class="col-12">
                        <div class="card">
                            <div class="card-header">
                                <h5><i class="fas fa-chart-bar"></i> 标准产品价格范围对比</h5>
                                <small class="text-muted">基于模糊匹配后的标准产品名称</small>
                            </div>
                            <div class="card-body position-relative">
                                <div id="priceComparisonChart" class="chart-container"></div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 趋势分析和产地分析 -->
                <div class="row mb-4">
                    <div class="col-md-6">
                        <div class="card">
                            <div class="card-header d-flex justify-content-between align-items-center">
                                <h5><i class="fas fa-line-chart"></i> 价格趋势分析</h5>
                                <select class="form-select form-select-sm w-auto" id="trendProductSelect">
                                    <option value="">加载中...</option>
                                </select>
                            </div>
                            <div class="card-body position-relative">
                                <div id="priceTrendChart" class="chart-container"></div>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="card">
                            <div class="card-header">
                                <h5><i class="fas fa-map-marker-alt"></i> 产地价格影响分析</h5>
                            </div>
                            <div class="card-body position-relative">
                                <div id="placeAnalysisChart" class="chart-container"></div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 详细数据表格 -->
                <div class="row">
                    <div class="col-12">
                        <div class="card">
                            <div class="card-header d-flex justify-content-between align-items-center">
                                <h5><i class="fas fa-table"></i> 详细数据列表</h5>
                                <div>
                                    <button class="btn btn-sm btn-outline-primary" onclick="exportData()">
                                        <i class="fas fa-download"></i> 导出数据
                                    </button>
                                    <button class="btn btn-sm btn-success" onclick="loadAllData()">
                                        <i class="fas fa-eye"></i> 显示所有数据
                                    </button>
                                </div>
                            </div>
                            <div class="card-body">
                                <div class="table-responsive" style="max-height: 600px; overflow-y: auto;">
                                    <table class="table table-striped table-hover">
                                        <thead class="table-dark sticky-top">
                                            <tr>
                                                <th>原始名称</th>
                                                <th>标准名称</th>
                                                <th>最低价格</th>
                                                <th>平均价格</th>
                                                <th>最高价格</th>
                                                <th>产地</th>
                                                <th>交易量</th>
                                                <th>市场类型</th>
                                                <th>发布日期</th>
                                                <th>数据质量</th>
                                            </tr>
                                        </thead>
                                        <tbody id="dataTableBody">
                                            <tr>
                                                <td colspan="10" class="text-center">
                                                    <div class="spinner-border text-primary" role="status">
                                                        <span class="visually-hidden">加载中...</span>
                                                    </div>
                                                </td>
                                            </tr>
                                        </tbody>
                                    </table>
                                </div>
                                <nav>
                                    <ul class="pagination justify-content-center" id="pagination">
                                        <!-- 动态加载 -->
                                    </ul>
                                </nav>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script>
        // 全局变量
        let currentPage = 1;
        let currentFilters = {};
        let currentSearch = '';
        let charts = {};
        let currentDataLimit = 5000;
        let filtersLoaded = false;
        let refreshStatusInterval = null;

        // 页面加载完成后初始化
        let autoRefreshInterval = null;

        $(document).ready(function() {
            console.log('页面初始化开始...');

            initializeFilters()
                .then(() => {
                    console.log('筛选器初始化完成，开始加载数据...');
                    loadOverview();
                    loadPriceComparison();
                    loadPriceTrend();
                    loadPlaceAnalysis();
                    loadDataTable();

                    // 初始化刷新状态
                    initRefreshStatus();
                })
                .catch(error => {
                    console.error('初始化失败:', error);
                    showErrorToast('初始化失败，请刷新页面重试');
                });

            bindEvents();

            // 这里是自动刷新代码
            autoRefreshInterval = setInterval(function() {
                manualRefreshData();
            }, 3600000);
            showInfoToast('已开启自动刷新，每一小时刷新一次');
        });

        // 页面卸载时清理定时器（可选，但推荐）
        $(window).on('beforeunload', function() {
            if (autoRefreshInterval) {
                clearInterval(autoRefreshInterval);
            }
            // 如果有其他定时器，也可以在这里清理
        });

        // 初始化刷新状态
        function initRefreshStatus() {
            console.log('初始化刷新状态监控...');
            checkRefreshStatus();
            refreshStatusInterval = setInterval(checkRefreshStatus, 30000);
        }

        // 检查刷新状态
        function checkRefreshStatus() {
            $.get('/api/refresh_status')
                .done(function(data) {
                    console.log('刷新状态:', data);
                    updateRefreshStatusDisplay(data);
                })
                .fail(function(xhr, status, error) {
                    console.error('获取刷新状态失败:', error);
                });
        }

        // 更新刷新状态显示
        function updateRefreshStatusDisplay(statusData) {
            if (statusData.last_refresh_time) {
                const refreshTime = new Date(statusData.last_refresh_time);
                $('#lastRefreshTime').text(refreshTime.toLocaleString());
            } else {
                $('#lastRefreshTime').text('未知');
            }
            
            const dataSourceText = statusData.data_source || '未知';
            const isHive = statusData.hive_available;
            
            $('#dataSourceStatus').text(dataSourceText);
            
            const indicator = $('#dataSourceIndicator');
            if (isHive) {
                indicator.removeClass('data-source-mock').addClass('data-source-hive');
                indicator.html('<i class="fas fa-database"></i> Hive数据库');
            } else {
                indicator.removeClass('data-source-hive').addClass('data-source-mock');
                indicator.html('<i class="fas fa-exclamation-triangle"></i> 模拟数据');
            }
            
            const totalRecords = statusData.total_records || 0;
            $('#totalRecordsStatus').text(totalRecords.toLocaleString());
        }

        // 手动刷新数据功能
        function manualRefreshData() {
            console.log('开始手动刷新数据...');
            
            const refreshBtn = $('#refreshBtn');
            const originalText = refreshBtn.html();
            
            refreshBtn.addClass('refreshing');
            refreshBtn.html('<i class="fas fa-sync-alt"></i> 刷新中...');
            
            const refreshToastId = showLoadingToast('正在从数据源刷新数据，请稍候...');
            
            $.ajax({
                url: '/api/refresh_data',
                method: 'POST',
                timeout: 120000,
                success: function(response) {
                    console.log('手动刷新响应:', response);
                    
                    if (response.status === 'success') {
                        showSuccessToast(`数据刷新成功！共 ${response.data_info.total_records.toLocaleString()} 条记录`);
                        
                        updateRefreshStatusDisplay({
                            last_refresh_time: response.timestamp,
                            data_source: response.data_info.data_source,
                            total_records: response.data_info.total_records,
                            hive_available: response.data_info.data_source.includes('Hive')
                        });
                        
                        setTimeout(() => {
                            loadOverview();
                            loadPriceComparison();
                            loadPriceTrend();
                            loadPlaceAnalysis();
                            loadDataTable();
                            initializeFilters();
                        }, 1000);
                        
                    } else if (response.status === 'warning') {
                        showWarningToast(response.message);
                        
                        updateRefreshStatusDisplay({
                            last_refresh_time: response.timestamp,
                            data_source: response.data_info.data_source,
                            total_records: response.data_info.total_records,
                            hive_available: false
                        });
                        
                        setTimeout(() => {
                            loadOverview();
                            loadPriceComparison();
                            loadPriceTrend();
                            loadPlaceAnalysis();
                            loadDataTable();
                            initializeFilters();
                        }, 1000);
                        
                    } else {
                        showErrorToast(response.message || '数据刷新失败');
                    }
                },
                error: function(xhr, status, error) {
                    console.error('手动刷新失败:', error);
                    
                    if (status === 'timeout') {
                        showErrorToast('数据刷新超时，请稍后重试');
                    } else {
                        showErrorToast(`数据刷新失败: ${error}`);
                    }
                },
                complete: function() {
                    refreshBtn.removeClass('refreshing');
                    refreshBtn.html(originalText);
                    $(`#${refreshToastId}`).remove();
                }
            });
        }

        // 事件绑定
        function bindEvents() {
            $('#trendProductSelect').change(function() {
                console.log('趋势产品选择变化:', $(this).val());
                loadPriceTrend();
            });

            $('#smartSearch').keypress(function(e) {
                if (e.which == 13) {
                    performSearch();
                }
            });

            $('#dataLimit').change(function() {
                currentDataLimit = parseInt($(this).val());
                console.log('数据限制变更为:', currentDataLimit);
                loadDataTable();
            });

            $('#productFilter, #placeFilter, #dateRange').change(function() {
                const filterId = $(this).attr('id');
                const filterValue = $(this).val();
                console.log(`筛选器 ${filterId} 变化:`, filterValue);
                updateFilterStatus();
            });

            $('#smartSearch').on('input', function() {
                const query = $(this).val().trim();
                if (query.length > 1) {
                    $.get('/api/search', {q: query, limit: 10}, function(data) {
                        console.log('搜索建议:', data.results);
                    });
                }
            });
        }

        // 初始化筛选器
        function initializeFilters() {
            return new Promise((resolve, reject) => {
                console.log('开始加载筛选器选项...');
                
                $.get('/api/filters')
                    .done(function(data) {
                        console.log('筛选器数据加载成功:', data);
                        
                        const productSelect = $('#productFilter');
                        const trendSelect = $('#trendProductSelect');
                        const placeSelect = $('#placeFilter');
                        
                        productSelect.empty();
                        trendSelect.empty();
                        placeSelect.empty();
                        
                        productSelect.append('<option value="">-- 选择产品 --</option>');
                        trendSelect.append('<option value="">-- 选择产品 --</option>');
                        placeSelect.append('<option value="">-- 选择产地 --</option>');
                        
                        const products = data.standard_products && data.standard_products.length > 0 
                            ? data.standard_products 
                            : data.products || [];
                        
                        console.log('可用产品:', products);
                        
                        products.forEach(product => {
                            if (product && product.trim()) {
                                productSelect.append(`<option value="${product}">${product}</option>`);
                                trendSelect.append(`<option value="${product}">${product}</option>`);
                            }
                        });
                        
                        const places = data.places || [];
                        console.log('可用产地:', places);
                        
                        places.forEach(place => {
                            if (place && place.trim()) {
                                placeSelect.append(`<option value="${place}">${place}</option>`);
                            }
                        });
                        
                        if (products.length > 0) {
                            trendSelect.val(products[0]);
                        }
                        
                        filtersLoaded = true;
                        console.log('筛选器选项加载完成');
                        resolve(data);
                    })
                    .fail(function(xhr, status, error) {
                        console.error('筛选器数据加载失败:', error);
                        showErrorToast('筛选器加载失败');
                        reject(error);
                    });
            });
        }

        // 更新筛选状态显示
        function updateFilterStatus() {
            const products = $('#productFilter').val() || [];
            const places = $('#placeFilter').val() || [];
            const dateRange = $('#dateRange').val();
            
            let statusText = '未应用筛选';
            let hasFilters = false;
            let statusClass = 'text-light';
            
            const statusParts = [];
            
            if (products.length > 0) {
                statusParts.push(`${products.length} 个产品`);
                hasFilters = true;
            }
            
            if (places.length > 0) {
                statusParts.push(`${places.length} 个产地`);
                hasFilters = true;
            }
            
            if (dateRange && dateRange !== '30') {
                statusParts.push(`${dateRange}天范围`);
                hasFilters = true;
            }
            
            if (hasFilters) {
                statusText = '已筛选: ' + statusParts.join(', ');
                statusClass = 'text-warning';
                $('.sidebar').addClass('filter-applied');
                
                if ($('#filterIndicator').length === 0) {
                    $('.sidebar h5').first().append(`
                        <span id="filterIndicator" class="badge bg-warning ms-2">
                            <i class="fas fa-filter"></i>
                        </span>
                    `);
                }
            } else {
                $('.sidebar').removeClass('filter-applied');
                $('#filterIndicator').remove();
            }
            
            $('#filterStatus').text(statusText).attr('class', statusClass);
        }

        // 智能搜索功能
        function performSearch() {
            currentSearch = $('#smartSearch').val().trim();
            currentPage = 1;
            
            console.log('执行搜索:', currentSearch);
            
            if (currentSearch) {
                showLoadingToast('搜索中...');
            }
            
            loadDataTable();
            
            if (currentSearch) {
                $.get('/api/search', {q: currentSearch}, function(data) {
                    if (data.results && data.results.total_found > 0) {
                        $('#currentShowingDisplay').text(`搜索到 ${data.results.total_found} 条`);
                        showSuccessToast(`找到 ${data.results.total_found} 条相关记录`);
                    } else {
                        showWarningToast('未找到相关记录');
                    }
                });
            }
        }

        // 加载所有数据
        function loadAllData() {
            if (confirm('确定要加载所有数据吗？这可能需要一些时间。')) {
                currentDataLimit = 100000;
                $('#dataLimit').val('100000');
                showLoadingToast('加载大量数据中，请稍候...');
                loadDataTable();
            }
        }

        // 加载概览数据
        function loadOverview() {
            console.log('加载概览数据...');
            
            const params = buildFilterParams();
            
            $.get('/api/overview', params)
                .done(function(data) {
                    console.log('概览数据:', data);
                    
                    $('#avgPriceToday').text((data.avg_price_today || 0).toFixed(2));
                    
                    const priceChange = data.price_change || 0;
                    const changeText = priceChange > 0 ? `↑${priceChange.toFixed(2)}` : 
                                     priceChange < 0 ? `↓${Math.abs(priceChange).toFixed(2)}` : '0';
                    $('#priceChange').text(changeText);
                    
                    $('#hotProducts').text((data.hot_products || []).slice(0, 3).join(', ') || '-');
                    $('#totalVolume').text((data.total_volume || 0).toLocaleString());
                    $('#lastUpdate').text(data.last_update ? data.last_update.substring(0, 16) : '-');
                    
                    $('#totalRecordsDisplay').text((data.total_records || 0).toLocaleString());
                    $('#uniqueProductsDisplay').text(data.unique_standard_products || data.unique_products || 0);
                    $('#uniquePlacesDisplay').text(data.unique_places || 0);
                    $('#dataCountBadge').text(`总数据: ${(data.total_records || 0).toLocaleString()} 条`);
                })
                .fail(function(xhr, status, error) {
                    console.error('概览数据加载失败:', error);
                    showErrorToast('概览数据加载失败');
                });
        }

        // 构建筛选参数
        function buildFilterParams() {
            const params = {};
            
            if (currentFilters.products && currentFilters.products.length > 0) {
                currentFilters.products.forEach(product => {
                    if (!params.products) params.products = [];
                    params.products.push(product);
                });
            }
            
            if (currentFilters.places && currentFilters.places.length > 0) {
                currentFilters.places.forEach(place => {
                    if (!params.places) params.places = [];
                    params.places.push(place);
                });
            }
            
            if (currentFilters.start_date) {
                params.start_date = currentFilters.start_date;
            }
            
            if (currentFilters.end_date) {
                params.end_date = currentFilters.end_date;
            }
            
            return params;
        }

        // 加载价格对比图表
        function loadPriceComparison() {
            console.log('加载价格对比图表...');
            
            showChartLoading('priceComparisonChart');
            
            const params = buildFilterParams();
            
            $.get('/api/price_comparison', params)
                .done(function(data) {
                    console.log('价格对比数据:', data);
                    
                    const chartDom = document.getElementById('priceComparisonChart');
                    if (charts.priceComparison) {
                        charts.priceComparison.dispose();
                    }
                    charts.priceComparison = echarts.init(chartDom);
                    
                    const option = {
                        title: {
                            text: '各标准产品价格范围对比',
                            left: 'center'
                        },
                        tooltip: {
                            trigger: 'axis',
                            axisPointer: {
                                type: 'shadow'
                            }
                        },
                        legend: {
                            data: ['最低价格', '平均价格', '最高价格'],
                            top: 30
                        },
                        xAxis: {
                            type: 'category',
                            data: data.categories || [],
                            axisLabel: {
                                rotate: 45
                            }
                        },
                        yAxis: {
                            type: 'value',
                            name: '价格(元/斤)'
                        },
                        series: [
                            {
                                name: '最低价格',
                                type: 'bar',
                                data: data.low_prices || [],
                                itemStyle: { color: '#91cc75' }
                            },
                            {
                                name: '平均价格',
                                type: 'bar',
                                data: data.avg_prices || [],
                                itemStyle: { color: '#fac858' }
                            },
                            {
                                name: '最高价格',
                                type: 'bar',
                                data: data.high_prices || [],
                                itemStyle: { color: '#ee6666' }
                            }
                        ]
                    };
                    
                    charts.priceComparison.setOption(option);
                    hideChartLoading('priceComparisonChart');
                })
                .fail(function(xhr, status, error) {
                    console.error('价格对比数据加载失败:', error);
                    hideChartLoading('priceComparisonChart');
                    showErrorToast('价格对比图表加载失败');
                });
        }

        // 加载价格趋势图表
        function loadPriceTrend() {
            const product = $('#trendProductSelect').val() || '萝卜';
            const params = buildFilterParams();
            params.product = product;
            
            console.log('加载价格趋势图表，产品:', product);
            
            showChartLoading('priceTrendChart');
            
            $.get('/api/price_trends', params)
                .done(function(data) {
                    console.log('价格趋势数据:', data);
                    
                    const chartDom = document.getElementById('priceTrendChart');
                    if (charts.priceTrend) {
                        charts.priceTrend.dispose();
                    }
                    charts.priceTrend = echarts.init(chartDom);
                    
                    const option = {
                        title: {
                            text: `${product}价格趋势`,
                            left: 'center'
                        },
                        tooltip: {
                            trigger: 'axis'
                        },
                        legend: {
                            data: ['最低价', '平均价', '最高价'],
                            top: 30
                        },
                        xAxis: {
                            type: 'category',
                            data: data.dates || []
                        },
                        yAxis: {
                            type: 'value',
                            name: '价格(元/斤)'
                        },
                        series: [
                            {
                                name: '最低价',
                                type: 'line',
                                data: data.low_prices || [],
                                smooth: true,
                                itemStyle: { color: '#91cc75' }
                            },
                            {
                                name: '平均价',
                                type: 'line',
                                data: data.avg_prices || [],
                                smooth: true,
                                itemStyle: { color: '#fac858' }
                            },
                            {
                                name: '最高价',
                                type: 'line',
                                data: data.high_prices || [],
                                smooth: true,
                                itemStyle: { color: '#ee6666' }
                            }
                        ]
                    };
                    
                    charts.priceTrend.setOption(option);
                    hideChartLoading('priceTrendChart');
                })
                .fail(function(xhr, status, error) {
                    console.error('价格趋势数据加载失败:', error);
                    hideChartLoading('priceTrendChart');
                    showErrorToast('价格趋势图表加载失败');
                });
        }

        // 加载产地分析图表
        function loadPlaceAnalysis() {
            console.log('加载产地分析图表...');
            
            showChartLoading('placeAnalysisChart');
            
            const params = buildFilterParams();
            
            $.get('/api/place_analysis', params)
                .done(function(data) {
                    console.log('产地分析数据:', data);
                    
                    const chartDom = document.getElementById('placeAnalysisChart');
                    if (charts.placeAnalysis) {
                        charts.placeAnalysis.dispose();
                    }
                    charts.placeAnalysis = echarts.init(chartDom);
                    
                    const option = {
                        title: {
                            text: '产地对价格的影响',
                            left: 'center'
                        },
                        tooltip: {
                            trigger: 'axis',
                            axisPointer: {
                                type: 'shadow'
                            }
                        },
                        legend: {
                            top: 30
                        },
                        xAxis: {
                            type: 'category',
                            data: data.categories || [],
                            axisLabel: {
                                rotate: 45
                            }
                        },
                        yAxis: {
                            type: 'value',
                            name: '平均价格(元/斤)'
                        },
                        series: data.series || []
                    };
                    
                    charts.placeAnalysis.setOption(option);
                    hideChartLoading('placeAnalysisChart');
                })
                .fail(function(xhr, status, error) {
                    console.error('产地分析数据加载失败:', error);
                    hideChartLoading('placeAnalysisChart');
                    showErrorToast('产地分析图表加载失败');
                });
        }

        // 加载数据表格
        function loadDataTable(page = 1) {
            const params = {
                page: page, 
                limit: currentDataLimit,
                search: currentSearch
            };
            
            if (currentFilters.products && currentFilters.products.length > 0) {
                currentFilters.products.forEach(product => {
                    if (!params.products) params.products = [];
                    params.products.push(product);
                });
            }
            
            if (currentFilters.places && currentFilters.places.length > 0) {
                currentFilters.places.forEach(place => {
                    if (!params.places) params.places = [];
                    params.places.push(place);
                });
            }
            
            if (currentFilters.start_date) {
                params.start_date = currentFilters.start_date;
            }
            
            if (currentFilters.end_date) {
                params.end_date = currentFilters.end_date;
            }
            
            console.log('加载数据表格，参数:', params);
            
            $('#dataTableBody').html(`
                <tr>
                    <td colspan="10" class="text-center">
                        <div class="spinner-border text-primary" role="status">
                            <span class="visually-hidden">加载中...</span>
                        </div>
                    </td>
                </tr>
            `);
            
            const urlParams = new URLSearchParams();
            Object.keys(params).forEach(key => {
                if (Array.isArray(params[key])) {
                    params[key].forEach(value => urlParams.append(key, value));
                } else {
                    urlParams.append(key, params[key]);
                }
            });
            
            $.get(`/api/data_table?${urlParams.toString()}`)
                .done(function(data) {
                    console.log('数据表格加载成功，记录数:', data.data ? data.data.length : 0);
                    console.log('后端返回的筛选结果:', data);
                    
                    $('#filteringProgress').remove();
                    
                    const tbody = $('#dataTableBody');
                    tbody.empty();
                    
                    if (data.data && data.data.length > 0) {
                        data.data.forEach(row => {
                            const qualityBadge = row.data_quality_score >= 90 ? 'bg-success' : 
                                               row.data_quality_score >= 80 ? 'bg-warning' : 'bg-danger';
                            
                            tbody.append(`
                                <tr>
                                    <td><span class="badge bg-info">${row.product_name}</span></td>
                                    <td><strong class="text-primary">${row.standard_product_name || row.product_name}</strong></td>
                                    <td>¥${row.low_price}</td>
                                    <td><strong class="text-success">¥${row.avg_price}</strong></td>
                                    <td>¥${row.high_price}</td>
                                    <td><span class="badge bg-secondary">${row.place}</span></td>
                                    <td>${(row.volume || 0).toLocaleString()}</td>
                                    <td><small class="text-muted">${row.market_type || '未知'}</small></td>
                                    <td>${row.pub_date}</td>
                                    <td><span class="badge ${qualityBadge}">${row.data_quality_score}%</span></td>
                                </tr>
                            `);
                        });
                        
                        showFilterResultsToast(data.total, data.data.length);
                    } else {
                        tbody.append(`
                            <tr>
                                <td colspan="10" class="text-center text-muted">
                                    <i class="fas fa-search fa-2x mb-2 text-muted"></i><br>
                                    没有找到符合筛选条件的数据<br>
                                    <small>请尝试调整筛选条件</small>
                                </td>
                            </tr>
                        `);
                        
                        showNoResultsToast();
                    }
                    
                    $('#currentShowingDisplay').text(`显示 ${data.data ? data.data.length : 0} 条`);
                    
                    updatePagination(data.page, data.total_pages || Math.ceil(data.total / data.limit), data.total);
                })
                .fail(function(xhr, status, error) {
                    console.error('数据表格加载失败:', error);
                    $('#filteringProgress').remove();
                    $('#dataTableBody').html(`
                        <tr>
                            <td colspan="10" class="text-center text-danger">数据加载失败，请重试</td>
                        </tr>
                    `);
                    showErrorToast('数据表格加载失败');
                });
        }

        // 更新分页
        function updatePagination(currentPage, totalPages, totalRecords) {
            const pagination = $('#pagination');
            pagination.empty();
            
            if (totalPages <= 1) return;
            
            pagination.append(`
                <li class="page-item ${currentPage === 1 ? 'disabled' : ''}">
                    <a class="page-link" href="#" onclick="loadDataTable(1)">首页</a>
                </li>
            `);
            
            pagination.append(`
                <li class="page-item ${currentPage === 1 ? 'disabled' : ''}">
                    <a class="page-link" href="#" onclick="loadDataTable(${currentPage - 1})">上一页</a>
                </li>
            `);
            
            const startPage = Math.max(1, currentPage - 2);
            const endPage = Math.min(totalPages, currentPage + 2);
            
            for (let i = startPage; i <= endPage; i++) {
                pagination.append(`
                    <li class="page-item ${i === currentPage ? 'active' : ''}">
                        <a class="page-link" href="#" onclick="loadDataTable(${i})">${i}</a>
                    </li>
                `);
            }
            
            pagination.append(`
                <li class="page-item ${currentPage === totalPages ? 'disabled' : ''}">
                    <a class="page-link" href="#" onclick="loadDataTable(${currentPage + 1})">下一页</a>
                </li>
            `);
            
            pagination.append(`
                <li class="page-item ${currentPage === totalPages ? 'disabled' : ''}">
                    <a class="page-link" href="#" onclick="loadDataTable(${totalPages})">末页</a>
                </li>
            `);
            
            pagination.append(`
                <li class="page-item disabled">
                    <span class="page-link">共 ${totalRecords.toLocaleString()} 条记录</span>
                </li>
            `);
        }

        // 应用筛选
        function applyFilters() {
            console.log('开始应用筛选条件...');
            
            if (!filtersLoaded) {
                showWarningToast('筛选器尚未加载完成，请稍候');
                return;
            }
            
            const dateRange = $('#dateRange').val();
            const products = $('#productFilter').val() || [];
            const places = $('#placeFilter').val() || [];
            
            console.log('前端筛选条件:', {
                dateRange: dateRange,
                products: products,
                places: places
            });
            
            currentFilters = {};
            currentPage = 1;
            
            if (products.length > 0) {
                currentFilters.products = products;
                console.log('设置产品筛选:', currentFilters.products);
            }
            
            if (places.length > 0) {
                currentFilters.places = places;
                console.log('设置产地筛选:', currentFilters.places);
            }
            
            if (dateRange && dateRange !== '30') {
                const endDate = new Date();
                const startDate = new Date();
                startDate.setDate(endDate.getDate() - parseInt(dateRange));
                
                currentFilters.start_date = startDate.toISOString().split('T')[0];
                currentFilters.end_date = endDate.toISOString().split('T')[0];
            }
            
            console.log('最终筛选条件:', currentFilters);
            
            updateFilterStatus();
            
            showFilteringProgress();
            
            loadOverview();
            loadPriceComparison();
            loadPriceTrend();
            loadPlaceAnalysis();
            loadDataTable();
        }

        // 添加筛选进度显示
        function showFilteringProgress() {
            const progressToast = $(`
                <div id="filteringProgress" class="toast position-fixed top-0 end-0 m-3" role="alert" style="z-index: 9999;">
                    <div class="toast-header">
                        <div class="spinner-border spinner-border-sm text-primary me-2" role="status"></div>
                        <strong class="me-auto">正在筛选数据</strong>
                    </div>
                    <div class="toast-body">
                        正在应用筛选条件，请稍候...
                    </div>
                </div>
            `);
            
            $('body').append(progressToast);
            new bootstrap.Toast(progressToast, {autohide: false}).show();
        }

        // 显示筛选结果提示
        function showFilterResultsToast(totalRecords, displayedRecords) {
            const hasFilters = Object.keys(currentFilters).length > 0 || currentSearch;
            
            if (hasFilters) {
                const toast = $(`
                    <div class="toast position-fixed top-0 end-0 m-3" role="alert" style="z-index: 9999;">
                        <div class="toast-header">
                            <i class="fas fa-filter text-success me-2"></i>
                            <strong class="me-auto">筛选完成</strong>
                            <button type="button" class="btn-close" data-bs-dismiss="toast"></button>
                        </div>
                        <div class="toast-body">
                            <strong>筛选结果：</strong><br>
                            找到 <span class="badge bg-primary">${totalRecords.toLocaleString()}</span> 条符合条件的记录<br>
                            当前显示 <span class="badge bg-success">${displayedRecords}</span> 条
                        </div>
                    </div>
                `);
                
                $('body').append(toast);
                new bootstrap.Toast(toast).show();
                
                setTimeout(() => {
                    toast.remove();
                }, 5000);
            }
        }

        // 显示无结果提示
        function showNoResultsToast() {
            const toast = $(`
                <div class="toast position-fixed top-0 end-0 m-3" role="alert" style="z-index: 9999;">
                    <div class="toast-header">
                        <i class="fas fa-exclamation-triangle text-warning me-2"></i>
                        <strong class="me-auto">无筛选结果</strong>
                        <button type="button" class="btn-close" data-bs-dismiss="toast"></button>
                    </div>
                    <div class="toast-body">
                        没有找到符合当前筛选条件的数据，请尝试：<br>
                        - 调整筛选条件<br>
                        - 扩大日期范围<br>
                        - 重置筛选条件
                    </div>
                </div>
            `);
            
            $('body').append(toast);
            new bootstrap.Toast(toast).show();
            
            setTimeout(() => {
                toast.remove();
            }, 8000);
        }

        // 重置筛选
        function resetFilters() {
            console.log('重置筛选条件');
            
            currentFilters = {};
            currentSearch = '';
            currentPage = 1;
            
            $('#dateRange').val('30');
            $('#productFilter').val([]);
            $('#placeFilter').val([]);
            $('#smartSearch').val('');
            
            updateFilterStatus();
            
            showLoadingToast('重置筛选条件中...');
            
            loadOverview();
            loadPriceComparison();
            loadPriceTrend();
            loadPlaceAnalysis();
            loadDataTable();
            
            setTimeout(() => {
                showSuccessToast('筛选条件已重置');
            }, 500);
        }

        // 导出数据功能
        function exportData() {
            console.log('开始导出数据...');
            
            const urlParams = new URLSearchParams();
            
            if (currentFilters.products && currentFilters.products.length > 0) {
                currentFilters.products.forEach(product => urlParams.append('products', product));
            }
            
            if (currentFilters.places && currentFilters.places.length > 0) {
                currentFilters.places.forEach(place => urlParams.append('places', place));
            }
            
            if (currentFilters.start_date) {
                urlParams.append('start_date', currentFilters.start_date);
            }
            
            if (currentFilters.end_date) {
                urlParams.append('end_date', currentFilters.end_date);
            }
            
            if (currentSearch) {
                urlParams.append('search', currentSearch);
            }
            
            urlParams.append('export', 'csv');
            
            showLoadingToast('正在准备导出文件...');
            
            const link = document.createElement('a');
            link.href = `/api/data_table?${urlParams.toString()}`;
            link.download = 'agriculture_data.csv';
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
            
            setTimeout(() => {
                showSuccessToast('数据导出已开始');
            }, 1000);
        }

        // 图表加载状态显示
        function showChartLoading(chartId) {
            const chartContainer = $(`#${chartId}`).parent();
            if (chartContainer.find('.loading-overlay').length === 0) {
                chartContainer.css('position', 'relative').append(`
                    <div class="loading-overlay">
                        <div class="spinner-border text-primary" role="status">
                            <span class="visually-hidden">加载中...</span>
                        </div>
                    </div>
                `);
            }
        }

        function hideChartLoading(chartId) {
            $(`#${chartId}`).parent().find('.loading-overlay').remove();
        }

        // Toast 提示函数
        function showToast(message, type = 'info') {
            const toastId = 'toast_' + Date.now();
            const iconMap = {
                'success': 'fa-check-circle text-success',
                'error': 'fa-exclamation-triangle text-danger',
                'warning': 'fa-exclamation-triangle text-warning',
                'info': 'fa-info-circle text-info',
                'loading': 'fa-spinner fa-spin text-primary'
            };
            
            const toast = $(`
                <div id="${toastId}" class="toast position-fixed top-0 end-0 m-3" role="alert" style="z-index: 9999;">
                    <div class="toast-header">
                        <i class="fas ${iconMap[type]} me-2"></i>
                        <strong class="me-auto">系统提示</strong>
                        <button type="button" class="btn-close" data-bs-dismiss="toast"></button>
                    </div>
                    <div class="toast-body">
                        ${message}
                    </div>
                </div>
            `);
            
            $('body').append(toast);
            const bsToast = new bootstrap.Toast(toast);
            bsToast.show();
            
            setTimeout(() => {
                toast.remove();
            }, type === 'loading' ? 10000 : 3000);
            
            return toastId;
        }

        function showSuccessToast(message) { return showToast(message, 'success'); }
        function showErrorToast(message) { return showToast(message, 'error'); }
        function showWarningToast(message) { return showToast(message, 'warning'); }
        function showInfoToast(message) { return showToast(message, 'info'); }
        function showLoadingToast(message) { return showToast(message, 'loading'); }

        // 响应式图表
        window.addEventListener('resize', function() {
            Object.values(charts).forEach(chart => {
                if (chart && chart.resize) {
                    chart.resize();
                }
            });
        });

        // 键盘快捷键支持
        $(document).keydown(function(e) {
            if (e.ctrlKey && e.keyCode === 70) {
                e.preventDefault();
                $('#smartSearch').focus();
            }
            
            if (e.keyCode === 27) {
                $('#smartSearch').val('');
                currentSearch = '';
                loadDataTable();
            }
            
            if (e.ctrlKey && e.keyCode === 82) {
                e.preventDefault();
                manualRefreshData();
            }
        });

        // 页面可见性API
        document.addEventListener('visibilitychange', function() {
            if (!document.hidden) {
                loadOverview();
                checkRefreshStatus();
            }
        });

        // 全局错误处理
        $(document).ajaxError(function(event, xhr, settings, thrownError) {
            console.error('AJAX请求失败:', settings.url, thrownError);
            
            if (xhr.status === 0) {
                showErrorToast('网络连接失败，请检查网络');
            } else if (xhr.status === 500) {
                showErrorToast('服务器内部错误，请稍后重试');
            } else {
                showErrorToast(`请求失败 (${xhr.status}): ${thrownError}`);
            }
        });

        // 工具提示初始化
        $(function () {
            $('[data-bs-toggle="tooltip"]').tooltip();
        });

        // 页面卸载时清理定时器
        $(window).on('beforeunload', function() {
            if (refreshStatusInterval) {
                clearInterval(refreshStatusInterval);
            }
        });
    </script>

    <!-- Toast容器 -->
    <div class="toast-container position-fixed top-0 end-0 p-3" style="z-index: 9999;">
        <!-- 动态生成的Toast将在这里显示 -->
    </div>
</body>
</html>

